package com.zyplayer.data.screen.framework.db.bean;

import com.zyplayer.data.screen.framework.db.executor.DatasourceUtil;
import com.zyplayer.data.screen.repository.manage.entity.DbDatasource;
import com.zyplayer.data.screen.service.manage.DbDatasourceService;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 需要声明注入的对象，只需要设置dbConfigList即可
 * databaseFactoryBeanList是后面生成的
 *
 * @author 暮光：城中城
 * @since 2018年8月8日
 */
@Repository
public class DatabaseRegistrationBean {
	
	@Resource
	DbDatasourceService dbDatasourceService;
	
	// 描述连接信息的对象列表
	private Map<Long, DatabaseFactoryBean> databaseFactoryBeanMap = new ConcurrentHashMap<>();
	
	public void removeDatabaseFactoryBean(Long sourceId) {
		DatabaseFactoryBean databaseFactoryBean = databaseFactoryBeanMap.remove(sourceId);
		if (databaseFactoryBean != null) {
			try {
				// 关闭数据源
				databaseFactoryBean.getDataSource().close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	public DatabaseFactoryBean getFactoryById(Long sourceId) {
		DatabaseFactoryBean databaseFactoryBean = databaseFactoryBeanMap.get(sourceId);
		if (databaseFactoryBean != null) {
			return databaseFactoryBean;
		}
		DbDatasource dbDatasource = dbDatasourceService.getById(sourceId);
		if (dbDatasource != null) {
			synchronized (DatabaseRegistrationBean.class) {
				databaseFactoryBean = databaseFactoryBeanMap.get(sourceId);
				if (databaseFactoryBean != null) {
					return databaseFactoryBean;
				}
				DatabaseFactoryBean databaseFactoryBeanNew = DatasourceUtil.createDatabaseFactoryBean(dbDatasource);
				if (databaseFactoryBeanNew != null) {
					databaseFactoryBeanMap.put(sourceId, databaseFactoryBeanNew);
				}
				return databaseFactoryBeanNew;
			}
		}
		return null;
	}
}
